'use strict';

/* Controllers */

var MeasurementApp = angular.module('MeasurementApp', []);
var sensordata;

MeasurementApp.controller('MeasurementListCtrl', ['$scope', '$http', '$log', function($scope, $http, $log, Measurement) {
  $http.get('http://odin.htwsaar.de:8080/measurements/newest').success(function(data) {
    //$scope.measurements = data._embedded.measurements; //localhost:8080/measurements
    $scope.measurements = data; //localhost:8080/measurements/newest

	//styleFunction ermittelt den Smog-Wert und Aussehen der Marker
	var styleCache = {};
	var styleFunction = function(feature, resolution) {
	    	var size = feature.get('features').length;
	    	var style = styleCache[size];
		var textval;
	   	var sumValue = 0;
		for (var i=0; i<size; i++) {
		    sumValue += feature.get('features')[i].get('value');
		}
		var averageValue = sumValue/size;
		textval = averageValue;
		
		var color;
		if(averageValue<10)
			color='#00FF00'
		if(averageValue>=10)
			color='#FF6600'
		if(averageValue>=20)
			color='#FF0000'
	    
	      style = [new ol.style.Style({
		image: new ol.style.Circle({
		  radius: 15,
		  stroke: new ol.style.Stroke({
		    color: '#fff'
		  }),
		  fill: new ol.style.Fill({
		    color: color //'#3399CC'
		  })
		}),
		text: new ol.style.Text({
		  text: textval,
		  fill: new ol.style.Fill({
		    color: '#000'
		  })
		})
		}
		)];
	      styleCache[size] = style;
	    
	    return style;
	  }

	//erstellt die Marker pro Smog-Sensor. Stellt sicher, dass immer nur 1 Wert pro Sensor angezeigt wird
	var sensorFeatures=[];
	var iconFeature; 
	
	var lastcoord="";
	angular.forEach($scope.measurements, function(sensor) {
		
		var long=parseFloat(sensor.longitude);
		var lat=parseFloat(sensor.latitude);

		if(lastcoord!=long +" "+ lat){
			$log.log("long:" + long +", lat:"+ lat+", val:"+sensor.value );
			
			lastcoord=long +" "+ lat;
			
			iconFeature= new ol.Feature({
			  geometry: new ol.geom.Point(ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')),
			  name: sensor.sensorId,
			  lat:sensor.latitude,
			  lon:sensor.longitude,
			  value:sensor.value  
			});
			
			sensorFeatures.push(iconFeature);
		}
	});

	//Erstellen des Layer der die Marker enthält 
	var vectorSource = new ol.source.Vector({
	  features: sensorFeatures
	});

	var clusterSource = new ol.source.Cluster({
	  distance: 40,
	  source: vectorSource
	});

	var iconStyle = new ol.style.Style({
	  image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
	    anchor: [0.5, 46],
	    anchorXUnits: 'fraction',
	    anchorYUnits: 'pixels',
	    opacity: 0.75,
	    src: 'http://www.google.com/intl/en_ALL/mapfiles/marker.png'
	  }))
	});

	var vectorLayer = new ol.layer.Vector({
	  
	    source: clusterSource, 
	    style: styleFunction 
	  
	});

	//Erstellt die iegentliche Map. Setzt einen Zoom auf Saarbrücken.
	var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            //source: new ol.source.MapQuest({layer: 'sat'})
		source: new ol.source.OSM()
          }), vectorLayer
        ],
        view: new ol.View({
          center: ol.proj.transform([6.95, 49.23 ], 'EPSG:4326', 'EPSG:3857'),
          zoom: 4
        })
      });


	//Zeigt Informationen bei einem Mausklick an
	var popup = new ol.Overlay.Popup();
	map.addOverlay(popup);

	map.on('click', function(evt) {
	    var prettyCoord = ol.coordinate.toStringHDMS(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'), 2);
	    popup.show(evt.coordinate, '<div><h2>Coordinates</h2><p>' + prettyCoord + '</p></div>');
	});

	//Zeigt Information wenn der Mauszeiger über einen Marker gelangt
	map.on("pointermove", function (evt) {
		var hit = this.forEachFeatureAtPixel(evt.pixel,
		        function(feature, layer) {
				var coord = ol.proj.transform(feature.getGeometry().getCoordinates(), 'EPSG:3857', 'EPSG:4326');
				var lon = coord[0];
				var lat = coord[1];
	    			popup.show(feature.getGeometry().getCoordinates(), '<div><h2>Coordinates</h2><p>' + lat +" "+ lon + '</p></div>');
		            return true;
		        }); 
	    });

	//Setz Zoom genau so, dass alle Marker zu sehen sind
	var extent = vectorSource.getExtent();
	map.getView().fitExtent(extent, map.getSize());

});

}]);
